<?php

namespace App\Http\Middleware;

use App\Lib\Code;
use App\Repositories\Criteria\RemitSettingCriteria;
use App\Repositories\Eloquent\PlatSettingRepository;
use App\Services\ApiResponseService;
use App\Services\RemitOrderService;
use Closure;
use Illuminate\Support\Facades\Auth;

class RemitAble
{
    protected $settingRepository;
    protected $remitRepository;

    public function __construct(PlatSettingRepository $platSettingRepository, RemitOrderService $remitOrderService)
    {
        $this->settingRepository = $platSettingRepository;
        $this->remitRepository = $remitOrderService;
        $this->settingRepository->pushCriteria(RemitSettingCriteria::class);
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $setting = $this->settingRepository->first();
        //若未配置出款设置 表示不能提现
        if ( ! $setting) {
            return ApiResponseService::showError(Code::FATAL_ERROR, '系统配置错误,不可提现');
        }

        $user = Auth::user();
        //判断用户是否有权限提现
        if ( ! $user->is_withdraw) {
            return ApiResponseService::showError(Code::NOTAUTH, '用户无此提现权限');
        }

        //判断是否绑定银行卡
        $bank = $user->bank()->default()->first();
        if ( ! $bank) {
            return ApiResponseService::showError(Code::UNBIND_BANK);
        }
        if ( ! $this->remitRepository->isRemitAble($user, $setting->value)) {
            return ApiResponseService::showError(Code::WITHDRAW_DISABLE);
        }

        return $next($request);
    }
}
